Week 13 - STEM 691

Interactive Maps

Dr. Kelly Boles

Weekly Check In/
Download .zip

Start Recording

Today’s Agenda


  • Weekly Check In
  • Final Projects
  • Revisiting Static Maps
  • Interactive maps with plotly
  • Collaborative Practice
  • Interactive maps with leaflet
  • Looking Ahead

Norms


In person norms And also, for online learning…
Be fully present to each other & the work. Keep your video on when possible. In large groups, mute your microphone when not talking. Close/mute/minimize other apps and devices to avoid distraction.
Assume positive intent & also take responsibility for the impact you have. Remember online interaction masks even more of the full story. Notice when you are making assumptions, and seek information to check them.
Embrace collaboration. Use the gallery view so you can see everyone. Use breakout groups as an opportunity to collaborate.
Be open to learning and accept non-closure. Expect the inevitable technical glitches and learning curves. Exercise patience with one another.
Be aware of when to step up and step back. When stepping back, do so as an active listener. Try out different modes of participation. Step back by making space for others to engage in these.
Land your plane–get to the point you intended. We all know how hard it is to be talked at, especially in a Zoom session, so let’s keep it to a minimum.

Final Projects

Final Projects


  • Presentations: Dec. 3rd
    • Slides on Course-wide Deck (see Canvas Assignment) prior to class
    • Each person will have 3-4 min to present
    • Feedback 3-4 min after
    • Non-presenters will complete feedback form for each presenter
  • Final Project Due: Dec. 10th
    • Should consider the feedback from your presentation
    • No late submissions/extensions
    • No written feedback on Canvas submission

Final Projects


  • Cleaning up your final file:
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
  • Put this in your setup chunk!

Static Maps

Static Maps - Roughly 3 Cases


  1. sf object & data (.csv) in same CRS
    • Yay! Easiest case
    • Some options:
      • left_join() data to sf object (if possible): plot one geom_sf() layer [Assn: 12]
      • Plot two geom_sf() layers (st_as_sf() data if needed)
      • Plot one geom_sf() layer with geom_point() [TODAY]
  2. sf object & data (.csv) in different CRS
    • Options
      • left_join() data to sf object: one geom_sf() layer [Australia]
      • st_transform() data to match sf object’s CRS: two geom_sf() layers [Knox Zones]
  3. sf object has multiple combined CRS/projections
    • More technical, but can be done
    • Ex. US projection in {ussf} (AK/HI problem)
    • Have to piece-wise re-project, transform

Interactive Maps in R

Interactive Maps in R


  • New York Times graphics editor Gregor Aisch noted that only 10 to 15 percent of readers who visit an interactive visualization on their site actually click on anything.
  • Is it worth the time and effort to make these things?

As with most design-related things, it depends on the goals and the audience of your visualization.

Interactivity


  • Immersion
  • Flexibility
  • Zooming, hover-over, pop-ups

Interactivity


Packages for interactive maps in R


  • plotly + ggplot
  • leaflet

Other packages include:

  • ggiraph + ggplot
  • highcharter

Start with a Static Map

Static Map


Our data: - The rgbif package allows you to access data from the Global Biodiversity Information Facility (GBIF).

#install.packages("rgbif")
library(rgbif)

Static Map


Our data: - The rgbif package allows you to access data from the Global Biodiversity Information Facility (GBIF).

monarchs <- occ_search(scientificName = 'Danaus plexippus') #provides a gbif object
monarch_data <- monarchs$data #provides a tibble

glimpse(monarch_data[,c(1:4,77)])
Rows: 500
Columns: 5
$ key              <chr> "4898204406", "4507686934", "4507704024", "4507984043…
$ scientificName   <chr> "Danaus plexippus (Linnaeus, 1758)", "Danaus plexippu…
$ decimalLatitude  <dbl> -28.39790, -34.90042, -34.86286, -26.45418, 28.47242,…
$ decimalLongitude <dbl> 153.40545, 138.69976, 139.39130, 152.63339, -16.25313…
$ lifeStage        <chr> NA, "Larva", "Adult", "Larva", "Adult", "Adult", "Pup…
  • Note: If you look at the help file ?occ_search(), it tells you that decimalLat/Long (aka: lat/long), is in CRS WGS84 (EPSG: 4326)

Static Map


  • The package {rnaturalearth} provides a map of countries of the world.

  • Use ne_countries() to pull country sf object and choose scale

# install.packages("rnaturalearth")
# install.packages("rnaturalearthdata")
library(sf)
library(rnaturalearth)

world <- ne_countries(scale = "medium", returnclass = "sf")
class(world)
[1] "sf"         "data.frame"
st_crs(world) #Yay! WGS84
Coordinate Reference System:
  User input: WGS 84 
  wkt:
GEOGCRS["WGS 84",
    DATUM["World Geodetic System 1984",
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["latitude",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["longitude",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    ID["EPSG",4326]]

Static Map: Plot base


First, let’s start with creating a base map of the world using ggplot2’s geom_sf().

library(ggplot2)

ggplot(data=world) +
  geom_sf(color = "white", linewidth = 0.1, fill = "#0C1337") +
  theme_minimal()

Static Map: Layer data


We can layer the Monarch butterfly data from monarch_data:

ggplot(data=world) +
  geom_sf(color = "white", linewidth = 0.1, fill = "#0C1337") +
  geom_point(data = monarch_data, aes(x = decimalLongitude, y = decimalLatitude,
                                      color = lifeStage), size = 0.5) +
  theme_minimal()

Adding Interactivity

ggplot() + plotly


  • plotly is an R package for creating interactive web-based graphs via the open source JavaScript graphing library plotly.js.
# install.packages("plotly")
library(plotly)

ggplot() + plotly


Use the function ggplotly() to draw the graph with plotly.js.

  • Printing the Plotly object will render the chart locally in your web browser or in the RStudio viewer

ggplot() + plotly


Wrap your plot p in ggplotly():

p <- ggplot(data=world) +
  geom_sf(color = "white", linewidth = 0.1, fill = "#0C1337") +
  geom_point(data = monarch_data, aes(x = decimalLongitude, y = decimalLatitude,
                                      color = lifeStage), size = 0.5) +
  theme_minimal()

ggplot() + plotly


Collaborative Practice

Leaftlet


Leaflet is an open-source JavaScript library for interactive maps.

  • Simplicity, performance, and usability
  • Lots of plugins and documentation

Leaflet


The leaflet R package makes it easy to create Leaflet maps from R.

#install.packages("leaflet")
library(leaflet)

Leaflet: Base Map


Create a base map with addTiles().

leaflet() |>
  addTiles()

Leaflet: Adding Components


The different components of the map can be added using the pipe operator |>.

However, some operations require the use of base R.

dplyr

mtcars |> 
  pull(hp)

base R

mtcars$hp

Leaflet: Provider Tiles


Specify different tile options with addProviderTiles

leaflet() |> 
  addProviderTiles(providers$Esri.NatGeoWorldMa)

Leaflet: Zoom


leaflet() |> 
  addProviderTiles(providers$Esri.NatGeoWorldMa) |> 
  setView(lng = -83.9294, lat = 35.9546, zoom = 14)

Leaflet: Markers and Tooltips


  • We can do things like add markers and tooltips.
leaflet() |>
  addProviderTiles(providers$Esri.NatGeoWorldMa) |>
  setView(lng = -83.9294, lat = 35.9546, zoom = 14) |>
  addMarkers(lng = -83.9294, lat = 35.9546,
             popup = "<a href='https://www.utk.edu/'>University of Tennessee, Knoxville</a>")

Leaflet: Bringing in Data


  • Add data when initializing the leaflet() function
  • ~ tells leaflet to look at the data
leaflet(monarch_data) |>
  addProviderTiles(providers$Esri.NatGeoWorldMa) |>
  setView(lng = -118.259,
          lat = 34.0507666,
          zoom = 6) |> 
  addCircles(
    ~ decimalLongitude,
    ~ decimalLatitude,
    popup =  ~ scientificName
  ) 

Leaflet: Bringing in Data


Leaflet: Customizing Maps


leaflet(monarch_data) |>
  addProviderTiles(providers$Esri.NatGeoWorldMa) |>
  setView(lng = -118.259,
          lat = 34.0507666,
          zoom = 6) |> 
  addCircles(
    ~ decimalLongitude,
    ~ decimalLatitude,
    popup =  ~ scientificName,
    weight = 9,
    radius = 40,
    color = "#ffa500",
    stroke = TRUE,
    fillOpacity = 0.8
  ) 

Leaflet: Customizing Maps


Leaflet: Adding Polygons


Specify a color scale for your polygons with fillColor.

leaflet(data = world) |>
  addTiles() |>
  addPolygons(
    fillColor = topo.colors(10, alpha = NULL),
    stroke = FALSE,
    label = ~ name
  )

Leaflet: Adding Polygons


Grad certificate


The University of Tennessee, Knoxville, offers an online graduate certificate in Educational Data Science for students interested in digital data collection, analysis, visualization, and more in educational settings. The certificate can be added to current graduate students’ studies or pursued as a stand-alone certificate for graduate-level students.

Looking Ahead

Looking Ahead


  • No weekly assignment.
  • Final Projects!